<template>
  <div class="_wz_addPaper">
    <Steps :current="testSteps">
      <Step title="基本信息" content="请填写考试对应的基本信息"></Step>
      <Step title="考题信息" content="试题素材添加完善"></Step>
    </Steps>
    <div style="padding:10px;height:calc(100% - 53px - 44px);overflow: auto;">
      <Form ref="formAdd" :model="formData" label-position="right" :label-width="80" :rules="ruleValidate" v-if="testSteps == 0">
        <FormItem label="运输企业" prop="deptUuid">
          <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable>
            <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="试卷名称" prop="materialExamName">
          <i-input v-model="formData.materialExamName" placeholder="请填写试卷名称" clearable />
        </FormItem>
        <FormItem label="试卷方向" prop="materialExamDirection">
          <i-select v-model="formData.materialExamDirection" filterable placeholder="请选择试卷方向" @on-change="public.selectName($event,formData,'materialExamDirectionName')" :label-in-value="true" clearable>
            <Option v-for="item in optionsData" :value="item.code" :key="item.code">{{ item.value }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="及格率" prop="materialExamPassRate" class="ivu-form-item-required">
          <i-select v-model.number="formData.materialExamPassRate" filterable placeholder="请选择及格率" clearable>
            <Option :value="1">100%</Option>
            <Option :value="0.8">80%</Option>
            <Option :value="0.6">60%</Option>
            <Option :value="0.5">50%</Option>
          </i-select>
        </FormItem>
        <FormItem label="上传试题" prop="materialExamQuestionUpload" class="ivu-form-item-required">
          <RadioGroup v-model.number="formData.materialExamQuestionUpload">
            <Radio :label="0">文件上传</Radio>
            <Radio :label="1">手动操作</Radio>
          </RadioGroup>
        </FormItem>

      </Form>
      <div v-if="testSteps == 1 && formData.materialExamQuestionUpload === 0">
        <Form label-position="right" :label-width="80">
          <FormItem label="试卷上传" class="ivu-form-item-required">
            <div>
              <Upload :before-upload="handleUpload" action="">
                <Button type="primary" icon="ios-cloud-upload-outline">请选择上传试卷文件</Button>
                {{fileName}}
              </Upload>
            </div>
          </FormItem>
          <FormItem label="注意事项">
            （一）所有文件格式以模板为准。<br />
            <span style="color: #ed4014;">（二）添加后，会自动上传至审核，如驳回后再次修改，会自动上传至审核。已经审核通过不可修改、删除。</span><br />
            （三）点击按钮下载模板文件进行填写
            <Button size="small" @click="fileDownload" type="primary">点击下载</Button>

          </FormItem>
          <div class="demo-upload-list">
            <img :src="tsImg" @error="public.imgDispose" />
            <div class="demo-upload-list-cover">
              <Icon type="ios-eye-outline" @click.native="handleView(tsImg)"></Icon>
            </div>
          </div>
        </Form>
      </div>
      <div v-if="testSteps == 1 && formData.materialExamQuestionUpload === 1" class="_wz__wz_addPaper_eaxm">
        <Card dis-hover :bordered="true">
          <p slot="title">手动添加试题</p>
          <!--公共的-->
          <p slot="extra">
            <Button type="primary" @click="tryAddFun">添加</Button>
          </p>
          <div style="height: 100%;" ref="tableH">
            <Table stripe highlight-row border :columns="columns" :data="tableData" :height="tableHeight"></Table>
          </div>
        </Card>
      </div>
    </div>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
      <Button type="primary" @click="lastStep" v-if="testSteps != 0">上一步</Button>
      <Button type="primary" @click="nextStep" v-if="testSteps != 1">下一步</Button>
      <Button type="primary" @click="addSubmit" v-if="testSteps != 0">提交</Button>
    </div>

    <!--试题添加-->
    <Modal v-model="tryAddType" :footer-hide="true" :mask-closable="false" title="添加">
      <Form ref="tryAdd" v-if="tryAddType" :model="tryAddData" label-position="right" :label-width="80" :rules="tryAddValidate">
        <FormItem label="试题题目" prop="question">
          <i-input v-model="tryAddData.question" type="textarea" :rows="4" placeholder="请填写试题题目" />
        </FormItem>
        <FormItem label="试题分数" prop="source">
          <i-input v-model.number="tryAddData.source" placeholder="请填写试题分数" clearable />
        </FormItem>
        <FormItem label="A选项" prop="optionA">
          <i-input v-model="tryAddData.optionA" placeholder="请填写A选项" clearable />
        </FormItem>
        <FormItem label="B选项" prop="optionB">
          <i-input v-model="tryAddData.optionB" placeholder="请填写B选项" clearable />
        </FormItem>
        <FormItem label="C选项" prop="optionC">
          <i-input v-model="tryAddData.optionC" placeholder="请填写C选项" clearable />
        </FormItem>
        <FormItem label="D选项" prop="optionD">
          <i-input v-model="tryAddData.optionD" placeholder="D选项" clearable />
        </FormItem>

        <FormItem label="试题类型" prop="optionType" class="ivu-form-item-required">
          <RadioGroup v-model="tryAddData.optionType" @on-change="optionTypeFun">
            <Radio :label="0" key="0">单选</Radio>
            <Radio :label="1" key="1">多选</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="正确答案" prop="wzAnswer">
          <i-select v-model="tryAddData.wzAnswer" filterable multiple allow-create v-if="tryAddData.optionType == 1">
            <Option value="A">A</Option>
            <Option value="B">B</Option>
            <Option value="C">C</Option>
            <Option value="D">D</Option>
          </i-select>
          <i-select v-model="tryAddData.wzAnswer" filterable allow-create v-if="tryAddData.optionType == 0">
            <Option value="A">A</Option>
            <Option value="B">B</Option>
            <Option value="C">C</Option>
            <Option value="D">D</Option>
          </i-select>
        </FormItem>
        <FormItem label="参考解析" prop="explanation">
          <i-input v-model="tryAddData.explanation" type="textarea" :rows="4" placeholder="请填写参考解析" />
        </FormItem>
        <FormItem>
          <Button style="margin-right: 8px" @click="tryAddType = false">取消</Button>
          <Button type="primary" @click="tryAddTypeFun">保存</Button>
        </FormItem>
      </Form>
    </Modal>
    <!--图片查看-->
    <Modal title="图片查看" v-model="visible" width="60%">
      <img :src="imgSrc" v-if="visible" @error="public.imgDispose" style="width: 100%">
    </Modal>
  </div>
</template>
<script>
  export default {
    props: ["selectData"],//接收来自父组件的数据
    data() {
      return {

        subDeptList :[],//下级企业
        uploadProgress: 0,//文件上传进度
        testSteps: 0,
        tsImg: require('../../../assets/zh.jpg'),
        imgSrc: "",
        visible: false,
        fileData: null,//选择的文件
        fileName: null,//文件名称
        formData: {},//提交的数据
        loading2: true,//表格加载
        ruleValidate: {//正则
          deptUuid: [
            {required: true, message: '请选择运输企业', trigger: 'blur'}
          ],
          materialExamName: [
            {required: true, message: '请填写试卷名称', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                value.length <= 20 ? callBack() : callBack('试卷名称最多可填写20个字符')
              }, trigger: 'blur'
            }
          ],
          materialExamDirection: [
            {required: true, message: '请选择试卷方向', trigger: 'blur'}
          ],
        },
        optionsData: [],//考试方向数据

        columns: [//表格表头数据
          {title: '序号', key: 'orderNum', width: 80},
          {title: '试题题目', key: 'question', minWidth: 220},
          {
            title: '试题类型', key: 'optionType', minWidth: 120, render: (h, params) => {
              return h('Tag', {
                props: {type: 'dot', color: params.row.optionType === 0 ? 'primary' : 'success'}
              }, params.row.optionType === 0 ? '单选' : '多选');
            }
          },//试题类型：0：单选，1多选
          {title: '试题分数', key: 'source', minWidth: 150},
          {title: 'A选项', key: 'optionA', minWidth: 120},
          {title: 'B选项', key: 'optionB', minWidth: 120},
          {title: 'C选项', key: 'optionC', minWidth: 120},
          {title: 'D选项', key: 'optionD', minWidth: 120},
          {title: '正确答案', key: 'answer', minWidth: 100},
          {title: '参考解析', key: 'explanation', minWidth: 160},
          {
            title: '操作', width: 120, fixed: 'right', render: (h, params, index) => {
              return h('div', [
                h('span', {
                  style: {"color": "#2d8cf0", "cursor": "pointer"},
                  on: {
                    click: () => {
                      params.row.wzAnswer = params.row.answer.split('');
                      this.tryAddData = params.row;
                      this.tryAddType = true;
                    }
                  }
                }, "修改"),
                h('Divider', {props: {type: 'vertical',}}, ''),
                h('span', {
                  style: {"color": "#2d8cf0", "cursor": "pointer"},
                  on: {
                    click: () => {
                      this.tableDelete(params.row)
                    }
                  }
                }, "删除")
              ]);
            }
          },
        ],
        tableHeight: 450,//表格默认高度
        tableData: [],//表格数据

        tryAddData: {},
        tryAddValidate: {
          question: [
            {required: true, message: '请填写试题题目', trigger: 'blur'},
          ],
          source: [
            {required: true, message: '请填写试题分数'},
            {type: 'number', message: '试题分数必须为数字值'},
            {
              validator: (rule, value, callBack) => {
                /^[1-9]\d*$/.test(value) ? callBack() : callBack('请输入正整数')
              }, trigger: 'blur'
            }
          ],
          optionA: [
            {required: true, message: '请填写A选项', trigger: 'blur'},
          ],
          optionB: [
            {required: true, message: '请填写B选项', trigger: 'blur'},
          ],
        },
        tryAddType: false,
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态

    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      let that = this;
      //加载方向
      that.axios.post(that.apiUrl.systemDictSystemDictList,{type:'training_direction'}).then(res => {
        if (!!res) {
          that.optionsData = res.data.data
        }
      }).catch(err => {
        console.log("失败", err)
      })



      if (!!that.selectData.id) {//修改
        that.formData = that.selectData;//表单
        that.formData.materialExamQuestionUpload = 1;

        delete that.formData.createTime;
      } else {
        that.formData.materialExamQuestionUpload = 0;
        that.formData.materialExamPassRate = 0.6;
        //判断内部 公共
        that.formData.materialExamOpen = 0;
      }


      //运输企业
      that.axios.post(that.apiUrl.coreDeptCoreDeptList,{}).then(res => {
        if (!!res) {
          that.subDeptList = res.data.data;
          if(!!that.selectData.id){
            that.formData.deptUuid = res.data.data[0].uuid;
          }
        }
      }).catch(err => {
        console.log("失败", err)
      })



    },
    methods: {//执行的方法
      //试题单选多选操作
      optionTypeFun(data) {//0 单选 1 多选
        let that = this;
        if (data === 0) {//单选
          that.tryAddData.wzAnswer = '';
        } else {
          that.tryAddData.wzAnswer = [];
        }
      },
      //手动添加试题 删除
      tableDelete(data) {
        let that = this;
        let num = data.orderNum;
        let dataList = JSON.parse(JSON.stringify(that.tableData))
        dataList.splice((num - 1), 1);
        for (let i = (num - 1); i < dataList.length; i++) {
          dataList[i].orderNum = i + 1;
        }
        that.$nextTick(function () {
          that.tableData = dataList;
        })
      },
      //试题添加
      tryAddTypeFun() {
        let that = this;
        that.$refs['tryAdd'].validate((valid) => {
          if (valid) {//正则判断使用
            if (that.tryAddData.wzAnswer.length > 1) {
              that.tryAddData.answer = that.tryAddData.wzAnswer.join("");
            } else {
              that.tryAddData.answer = that.tryAddData.wzAnswer;
            }
            //orderNum 判断有没有序号
            if (!!that.tryAddData.orderNum) {
              that.tableData[that.tryAddData.orderNum - 1] = that.tryAddData;
            } else {
              that.tryAddData.orderNum = that.tableData.length + 1;
              that.tableData.push(that.tryAddData);
            }
            that.tryAddType = false;
          }
        })
      },
      //试题弹出
      tryAddFun() {
        let that = this;
        that.tryAddData = {
          optionType: 0,
          wzAnswer: []
        };
        that.tryAddType = true;
      },
      //上一步
      lastStep() {
        this.testSteps = 0;
      },
      //下一步
      nextStep() {
        let that = this;
        //根据materialExamQuestionUpload  1 加载list
        //如果新增 不请求
        //如果修改 请求
        that.$refs['formAdd'].validate((valid) => {
          if (valid) {//正则判断使用
            that.testSteps = 1;

            if (that.formData.materialExamQuestionUpload === 1) {//如果手动添加 计算表格高度
              if (!!that.selectData.id) {
                //单选 多选 下拉 数据
                that.axios.post(that.apiUrl.webApi + "/educate/materialExam/materialExamQuestionList",{materialUuid:that.formData.uuid}).then(res => {
                  if (!!res) {
                    that.tableData = res.data.data
                  }
                }).catch(err => {
                  console.log('失败', err);
                })
              }
              that.$nextTick(function () {
                that.tableHeight = that.$refs.tableH.offsetHeight;
                window.onresize = ()=> {
                  that.tableHeight = that.$refs.tableH.offsetHeight;
                };
              })
            }
          }
        })
      },
      handleUpload(file) {
        let that = this;
        //判断文件类型
        let type = file.name.substr((file.name.lastIndexOf(".") + 1));
        if (type == "XLSX" || type == "xlsx" || type == "XLS" || type == "xls") {//xls
          that.fileData = file;
        } else {
          that.$Message.error('您上传试卷文件类型不匹配');
          return false;
        }
        that.file = file;
        that.fileName = file.name;
        return false;
      },
      addSubmit() {
        let that = this;
        let data = that.formData;
        let formData = new FormData();
        if (that.formData.materialExamQuestionUpload === 0) {//文件上传

          if (!!!that.file) {
            if (!!!that.selectData.id) {
              that.$Message.error('请上传试卷文件素材');
              return false;
            }
          }else{
            formData.append('multipartFile', that.fileData);
          }
        }else{
          if (that.tableData.length <= 0) {
            that.$Message.error('请添加考试试题');
            return false;
          }
          data.examQuestion = JSON.stringify(that.tableData);
        }




        for (let key in data) {
          if(!!data[key] && data[key] != 'null'){
            formData.append(key, data[key]);
          }
        }


        that.axios.post(that.apiUrl.webApi + "/educate/materialExam/materialExamSaveOrUpdate", formData,that.public.parameterUploadProgress(that)).then(res => {
          that.$Spin.hide();
          if (!!res) {
            that.$Message.success("保存成功");
            that.$emit("closeFun", true)
          }
        }).catch(err => {
          console.log("失败", err)
        })
      },
      //文件下载
      fileDownload() {
        window.open(this.apiUrl.imgUrl +"template/安运通/考试测验导入模板.xlsx", '_blank')
      },
      //缩略图查看
      handleView(src) {
        this.imgSrc = src;
        this.visible = true;
      },
    },
    watch: {//监听

    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态
      window.onresize = null;
    }
  }
</script>
<style lang="less">
  ._wz_addPaper {
    ._wz__wz_addPaper_eaxm {
      height: 100%;
      display: flex;
      flex-direction: column;
    }


    .demo-upload-list {
      margin: auto;
      display: block;
      text-align: center;
      line-height: 60px;
      border: 1px solid transparent;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      box-shadow: 0 1px 1px rgba(0, 0, 0, .2);

      img {
        width: 100%;
        height: 100%;
      }

      .demo-upload-list-cover {
        align-items: center;
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);

        i {
          display: block;
          margin: auto;
          color: #fff;
          font-size: 40px;
          cursor: pointer;
        }
      }
    }


    .demo-upload-list:hover .demo-upload-list-cover {

      display: flex;
    }
  }

</style>
